#! /usr/bin/python
# This script uses resources of ABBYY Lingvo Online
#   and is capable of ru-en/en-ru translation now
# Usage:
#   lingvo 'word'
# This program is BEERWARE;
# you can read, nodify and steal it without restrictions
# Apr 2011, Dmytro Sirenko

"""
To translate a word using Lingvo Online, use function 
translate() from this module
"""

from HTMLParser import HTMLParser
import urllib2

class HTMLRipper(HTMLParser):
    def __init__(self, tag, attr):
        HTMLParser.__init__(self)
        self.sought_tag = tag
        self.sought_attr = dict(attr)

    def handle_starttag(self, tag, attrs):
        if tag == self.sought_tag:
            self.nestness += 1
            if self.depth_found == 0 and self.attr_found(attrs):
                self.depth_found = self.nestness
        if self.depth_found > 0:
            if tag.lower() in ('div', 'p'): self.txt += '\n'
            #self.txt += '<' + tag + str(attrs) + '>'

    def handle_endtag(self, tag):
        if self.depth_found > 0:
            pass #self.txt += ''
        if tag == self.sought_tag:
            if self.nestness == self.depth_found:
                self.depth_found = 0
            self.nestness -= 1
    
    def handle_data(self, text):
        if self.depth_found > 0:
            if not text.isspace(): self.txt += text
    
    def attr_found(self, attrs):
        dattrs = dict(attrs)
        for attr_name in dattrs:
            if attr_name in self.sought_attr:
                if dattrs[attr_name] == self.sought_attr[attr_name]:
                    return True
        return False

    def seek_in(self, data):
        self.nestness = 0
        self.depth_found = 0
        self.txt = ''

        self.feed(data)
        return self.txt

def from_to(word):
    try:
        uword = unicode(word, 'ascii')
        return 'en-ru'
    except UnicodeDecodeError:
        return 'ru-en'

def translate(word):
    url = 'http://lingvo.abbyyonline.com/en/' + from_to(word) + '/' + word
    page = urllib2.urlopen(url)
    data = ''
    for line in page:
        data += line

    ripper = HTMLRipper('div', {'class':'lol-cards'})
    return ripper.seek_in(data)

if __name__ == '__main__':
    import sys
    if len(sys.argv) < 2:
        print('Must supply a word to translate as an argument')
        sys.exit(1)
    
    print translate(sys.argv[1])
